﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace PIMS.glb
{
    public class RegistryTool
    {
        /// <summary>
        /// 读注册表
        /// </summary>
        /// <param name="keypath">注册表键值路径，例@"SOFTWARE\test"</param>
        /// <param name="keyname">注册表键值名称</param>
        /// <returns>值</returns>
        public static string ReadReg(string keypath, string keyname)
        {
            string result = "";
            try
            {
                RegistryKey hklm = Registry.LocalMachine;
                RegistryKey hkSoftWare = hklm.OpenSubKey(keypath, false);
                result = hkSoftWare.GetValue(keyname,"").ToString();
                hklm.Close();
                hkSoftWare.Close();
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
                try
                {
                    RegistryKey key = Registry.LocalMachine;
                    RegistryKey software = key.CreateSubKey(keypath);
                }
                catch (Exception ex2)
                {
                    Console.WriteLine(ex2.Message);
                    MessageBox.Show(ex2.Message);
                }
               // MessageBox.Show(ex.Message);
            }
            return result;
        }
        /// <summary>
        /// 写注册表
        /// </summary>
        /// <param name="keypath">注册表键值路径，例@"SOFTWARE\test"</param>
        /// <param name="keyname">注册表键值名称</param>
        /// <param name="keyvalue">值</param>
        public static void WriteReg(string keypath,string keyname,string keyvalue)
        {
            try
            {
                RegistryKey hklm = Registry.LocalMachine;
                RegistryKey hkSoftWare = hklm.OpenSubKey(keypath, true);
                hkSoftWare.SetValue(keyname, keyvalue, RegistryValueKind.String);
                hklm.Close();
                hkSoftWare.Close();
            }
            catch(Exception ex)
            {
                try
                {
                    RegistryKey key = Registry.LocalMachine;
                    RegistryKey software = key.CreateSubKey(keypath);
                    software.SetValue(keyname, keyvalue, RegistryValueKind.String);
                    key.Close();
                    software.Close();
                }
                catch (Exception ex2)
                {
                    Console.WriteLine(ex2.Message);
                    MessageBox.Show(ex2.Message);
                }
                //MessageBox.Show(ex.StackTrace,ex.Message);
            }

        }
    }
}
